﻿/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF WIKIX.
WIKIX IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

WIKIX IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH WIKIX. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
using EPiServer.Core;
using System.Security;
using EPiServer.Security;

namespace EPiServer.Research.Wiki.Core
{
    public class WikiRouteHandler : IRouteHandler
    {
        public PageReference WikiRoot { get; private set; }
        public string VirtualPath { get; set; }
        public AccessLevel ReqAccess { get; set; }
        
        /// <summary>
        /// Constructor, set when RouteHandler is assigned to route.
        /// </summary>
        /// <param name="WikiRoot">Reference to root page of the Wiki</param>
        public WikiRouteHandler(PageReference WikiRoot, string VirtualPath, AccessLevel ReqAccess)
        {
            this.WikiRoot = WikiRoot;
            this.VirtualPath = VirtualPath;
            this.ReqAccess = ReqAccess;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            //Check if user has create permissions to WikiRoot - if not, 404
            if ((ReqAccess!=AccessLevel.Undefined) && !DataFactory.Instance.GetPage(WikiRoot).QueryDistinctAccess(ReqAccess)) 
                throw new HttpException(404, "Page Not Found");

            //Send parameters to NewPage
            foreach (var value in requestContext.RouteData.Values)
            {
                requestContext.HttpContext.Items[value.Key] = value.Value;
            }

            //Create a Page, based on the NewPage template to handle the new page
            var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath,typeof(PageBase)) as PageBase;
            page.CurrentPageLink = WikiRoot;
            

            return page as IHttpHandler;
        }
    }



}
